/*
 * Copyright (c) 2023-2024 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.system.sys.controller;

import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang3.RandomStringUtils;
import org.elsfs.cloud.common.core.vo.R;
import org.elsfs.cloud.common.util.security.RandImageUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/** CommonController */
@RestController
@RequestMapping("/sys")
@Slf4j
@RequiredArgsConstructor
public class CommonController {
  private static final String BASE_CHECK_CODES =
      "qwertyuiplkjhgfdsazxcvbnmQWERTYUPLKJHGFDSAZXCVBNM1234567890";

  /** 签名密钥串(字典等敏感接口) @TODO 降低使用成本加的默认值,实际以 yml配置 为准 */
  private static final String signatureSecret = "dhhdu34mj34jh34h34tk3k4h";

  private final RedisTemplate<String, Object> redisTemplate;

  /**
   * 后台生成图形验证码 ：有效
   *
   * @param response response
   * @param key key
   */
  @Schema(name = "获取验证码")
  @GetMapping(value = "/randomImage/{key}")
  public R<String> randomImage(HttpServletResponse response, @PathVariable("key") String key) {
    R<String> res = new R<String>();
    try {
      // 生成验证码
      String code = RandomStringUtils.random(4, BASE_CHECK_CODES);
      // 存到redis中
      String lowerCaseCode = code.toLowerCase();

      // update-begin-author:taoyan date:2022-9-13 for: VUEN-2245 【漏洞】发现新漏洞待处理20220906
      // 加入密钥作为混淆，避免简单的拼接，被外部利用，用户自定义该密钥即可
      String origin = lowerCaseCode + key + signatureSecret;
      String realKey = Md5Crypt.apr1Crypt(origin);
      // update-end-author:taoyan date:2022-9-13 for: VUEN-2245 【漏洞】发现新漏洞待处理20220906
      redisTemplate.opsForValue().set(realKey, lowerCaseCode, 60);
      LOGGER.info("获取验证码，Redis key = {}，checkCode = {}", realKey, code);
      // 返回前端
      String base64 = RandImageUtils.generate(code);
      res.setCode(0);
      res.setResult(base64);
    } catch (Exception e) {
      LOGGER.error(e.getMessage(), e);
      res.setMessage("获取验证码失败,请检查redis配置!");
      return res;
    }
    return res;
  }
}
